package com.ly.hotel.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.TabHostActivity;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.msgevent.CloseAdEvent;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.spainterface.jxd.activity.JxdJSPopupWindow;
import com.ly.hotel.spainterface.jxd.activity.JxdXiaoFeiPopupWindow;
import com.ly.hotel.spainterface.jxd.dialog.BillQuerySwipeDialog;
import com.ly.hotel.spainterface.jxd.dialog.JiShiWorkDialog;
import com.ly.hotel.util.DensityUtil;
import com.ly.hotel.adaptor.NetworkUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.util.bugtrace.CrashHandler;
import com.ly.hotel.view.InitActivity;
import com.ly.hotel.view.common.CustomDialog;
import com.ly.hotel.view.common.ToolsDialog;
import com.ly.hotel.view.liuwei.InputHandNoActivity;
import com.tencent.bugly.crashreport.CrashReport;

import de.greenrobot.event.EventBus;

public class FxService extends Service {
	// 定义浮动窗口布局
	private static RelativeLayout mFloatLayout;
	private LayoutParams wmParams;
	// 创建浮动窗口设置布局参数的对象
	private WindowManager mWindowManager;

	private ImageView mFloatView;
	
	private TextView tips_text;
	
	private static final String TAG = "FxService";
	private float upx = 0;
	private float upy = 0;
	private float lastX = 0;
	private float lastY = 0;

	private MyApplication app;

	private Handler handler;
	private static ToolsDialog.Builder builder = null;
	private static CustomDialog.Builder dialog = null;
	private static Context context;
	private Timer fx_timer;
	private boolean pointTransparentEd = true;
	private boolean showPingMs = false;
	private static boolean ismenuShow = false;
	
	private static ToolsDialog d = null;
	private static BillQuerySwipeDialog billDialog = null;
	private static JiShiWorkDialog workDialog = null;
	@Override
	public void onCreate() {
		super.onCreate();
		app = (MyApplication) getApplicationContext();
		context = getBaseContext();
		builder = new ToolsDialog.Builder(this);
		dialog = new CustomDialog.Builder(this);
		createFloatView();

		handler = new Handler();// handler = new Handler(Looper.getMainLooper());使用Looper.getMainLooper()这个会导致开机按技师导致死机

		registerReceiver(bottomMenuRev, new IntentFilter(Constants.Broadcast.CALL_MENU));

		sendBroadcast(new Intent(Constants.Broadcast.CALL_MENU).putExtra("flag", Constants.POINT_OPEN));
		
		if(!Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA801_NAME)){
			String enable = SysConf.extendConfGetValue(SysConf.SYS_CONF_FACTORY_DEBUG, "");
			if (enable.equals("1")) {
				showPingMs = true;
			}
			testServer();
		}
	}
	
	private void setBgTransparentDelay() {
		if (fx_timer != null) {
			fx_timer.cancel();
		}
		fx_timer = new Timer(true);

		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				sendBroadcast(new Intent(Constants.Broadcast.CALL_MENU).putExtra("flag", Constants.POINT_IDLE));
				fx_timer.cancel();
				fx_timer = null;
				pointTransparentEd = true;
			}
		};
		fx_timer.schedule(task, 3000);
	}

	private static boolean isSpaInBackground() {
		String packName = ((MyApplication) MyApplication.getContext()).getTopActivity();

		if (!packName.contains("com.ly.hotel")) {
			return true;
		}
		
		return false;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	private void createFloatView() {
		wmParams = new LayoutParams();
		getApplication();
		// 获取WindowManagerImpl.CompatModeWrapper
		mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);

		DisplayMetrics dm = new DisplayMetrics();
		mWindowManager.getDefaultDisplay().getMetrics(dm);

		// 设置window type
		if (Build.VERSION.SDK_INT < 19) {
			//安卓4.4以下的使用这个
			wmParams.type = LayoutParams.TYPE_PHONE;
		} else {
			//在S905上面出现了小圆点不能操作的问题
			//解决方法来源-http://www.liaohuqiu.net/cn/posts/android-windows-manager/
			wmParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
		}
		// 设置图片格式，效果为背景透明
		wmParams.format = PixelFormat.RGBA_8888;
		// 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		wmParams.flags =
		// LayoutParams.FLAG_NOT_TOUCH_MODAL |
		LayoutParams.FLAG_NOT_FOCUSABLE
				//LayoutParams.FLAG_ALT_FOCUSABLE_IM
		// LayoutParams.FLAG_NOT_TOUCHABLE
		;

		// 调整悬浮窗显示的停靠位置为左侧置顶
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;
		// 以屏幕左上角为原点，设置x、y初始值
		lastX = getResources().getDimension(R.dimen.px1815);
		lastY = getResources().getDimension(R.dimen.px480);
		wmParams.x = (int) lastX;
		wmParams.y = (int) lastY;

		/*
		 * // 设置悬浮窗口长宽数据 wmParams.width = 200; wmParams.height = 80;
		 */

		// 设置悬浮窗口长宽数据
		wmParams.width = LayoutParams.WRAP_CONTENT;
		wmParams.height = LayoutParams.WRAP_CONTENT;

		LayoutInflater inflater = LayoutInflater.from(getApplication());
		// 获取浮动窗口视图所在布局
		mFloatLayout = (RelativeLayout) inflater.inflate(R.layout.float_layout, null);
		
		// 添加mFloatLayout
		mWindowManager.addView(mFloatLayout, wmParams);
		
		// 浮动窗口按钮
		mFloatView = (ImageView) mFloatLayout.findViewById(R.id.float_id);
		tips_text = (TextView) mFloatLayout.findViewById(R.id.tips_text);
		mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
				View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		mFloatLayout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// 刷新
				if (pointTransparentEd) {
					View vv = mFloatLayout.findViewById(R.id.float_id);
					vv.setBackgroundResource(R.mipmap.point);
					vv = null;
					pointTransparentEd = false;
				}
				setBgTransparentDelay();

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					// 记录点击时距离起始点的位置
					upx = event.getRawX() - wmParams.x;
					upy = event.getRawY() - wmParams.y;
					break;
				case MotionEvent.ACTION_MOVE:
					wmParams.x = (int) (event.getRawX() - upx);
					wmParams.y = (int) (event.getRawY() - upy);
					if (wmParams.y <= DensityUtil.dip2px(70)) {
						wmParams.y = DensityUtil.dip2px(70);
					}
					mWindowManager.updateViewLayout(mFloatLayout, wmParams);
					break;
				case MotionEvent.ACTION_UP:

					if (Math.abs(lastX - wmParams.x) > DensityUtil.dip2px(10) || Math.abs(lastY - wmParams.y) > DensityUtil.dip2px(10)) {
						lastX = wmParams.x;
						lastY = wmParams.y;
						break;
					}

					lastX = wmParams.x;
					lastY = wmParams.y;

					v.performClick();
					
					open();
					break;
				}
				return false;
			}
		});
	}
	public static void open(){
		if(!ismenuShow){
			ismenuShow = true;
		} else {
			return;
		}

		final String name = ((MyApplication) MyApplication.getContext()).getTopActivity();

		builder = new ToolsDialog.Builder(context);
			//本软件有bug，在主页的任何界面，按返回主页是有问题的，所以在这个activity屏蔽这个按键
		builder.setHomeButton(new OnClickListener() {
			@Override
			public void onClick(DialogInterface di, int arg1) {
				backHome(true);
			}
		});
		if(((MyApplication) MyApplication.getContext()).isBtnItemEnable("呼叫")){//如果开通了功能，就显示之

			String callTxt = "";
			if (((MyApplication) MyApplication.getContext()).getCallStatus() == Constants.CALL_CANCLE) {
				callTxt = context.getString(R.string.call);
			} else if (((MyApplication) MyApplication.getContext()).getCallStatus() == Constants.CALL_REQUEST) {
				callTxt = context.getString(R.string.callCancle);;
			}

			builder.setCallButton(callTxt, new OnClickListener() {
				@Override
				public void onClick(DialogInterface di, int arg1) {
					new Thread(new Runnable() {
						@Override
						public void run() {
							((MyApplication) MyApplication.getContext()).changeLight();
						}

					}).start();

					if(((MyApplication) MyApplication.getContext()).getCallStatus() == Constants.CALL_CANCLE){
						EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_POINT_CALL));
					}else{
						EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_POINT_CANCLE_CALL));
					}
					di.dismiss();
				}
			});
		}

		builder.setLangButton(new OnClickListener() {
			@Override
			public void onClick(DialogInterface di, int arg1) {
				changeLanguage();
			}
		});
		//spa不在前台不支持留位
		if(!isSpaInBackground()){
			if (MyApplication.myLicenseGetValue("留位").equals(1)) {
				builder.setLiuweiButton(new OnClickListener() {
					@Override
					public void onClick(DialogInterface di, int arg1) {
						di.dismiss();
						InputHandNoActivity dialog = new InputHandNoActivity(context, R.style.InputDialog);// 创建Dialog并设置样式主题
						dialog.setCanceledOnTouchOutside(false);
						dialog.getWindow().setType(LayoutParams.TYPE_SYSTEM_ALERT);
						dialog.show();
						EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_LIUWEI_WAIT));
					}
				});
			}
		}

		if(MyApplication.interfaceVersion.contains("JXD")){
			builder.setBillButtonClickListener(new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					if(billDialog == null){
						billDialog = new BillQuerySwipeDialog(MyApplication.getContext(), R.style.InputDialog);// 创建Dialog并设置样式主题
						billDialog.setCanceledOnTouchOutside(true);
						billDialog.getWindow().setType(LayoutParams.TYPE_PHONE);
						billDialog.show();
					}else{
						if (!billDialog.isShowing()){
							billDialog.show();
							billDialog.initDialog();
						}
					}

				}
			});

			builder.setJishiButtonClickListener(null, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					Intent intentJiShi = new Intent(context, JxdJSPopupWindow.class);
					context.startService(intentJiShi);
				}
			});

			builder.setXiaofeiButtonClickListener(null, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					Intent intentXiaoFei = new Intent(context, JxdXiaoFeiPopupWindow.class);
					context.startService(intentXiaoFei);
				}
			});

			builder.setWorkBeginButtonClickListener(new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					jishiWork(0);
				}
			});

			builder.setWorkAddButtonClickListener(new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					jishiWork(2);
				}
			});

			builder.setWorkEndButtonClickListener(new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					jishiWork(1);
				}
			});
		} else if(MyApplication.interfaceVersion.contains("NM")){
			builder.setBillButtonClickListener(new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					ToastUtil.showShortToast(context, "暂未开通该功能", 4000);
				}
			});

			builder.setJishiButtonClickListener(context.getString(R.string.menu_jishi), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					ToastUtil.showShortToast(context, "暂未开通该功能", 4000);
				}
			});

			builder.setXiaofeiButtonClickListener(context.getString(R.string.menu_xiaofei), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					ToastUtil.showShortToast(context, "暂未开通该功能", 4000);
				}
			});

			builder.setWorkBeginButtonClickListener(new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					ToastUtil.showShortToast(context, "暂未开通该功能", 4000);
				}
			});

			builder.setWorkEndButtonClickListener(new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					ToastUtil.showShortToast( context, "暂未开通该功能", 4000);
				}
			});
		}

		d = builder.create();
		d.getWindow().setType(LayoutParams.TYPE_SYSTEM_ALERT);
		d.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss(DialogInterface arg0) {
				// TODO Auto-generated method stub
				ismenuShow = false;
			}
		});

		d.show();
	}

	//技师上钟、加钟、上钟
	private static void jishiWork(int type){
		if(workDialog == null) {
			workDialog = new JiShiWorkDialog(MyApplication.getContext(), R.style.jishiPopDialog);// 创建Dialog并设置样式主题
			workDialog.setCanceledOnTouchOutside(false);
			workDialog.getWindow().setType(LayoutParams.TYPE_PHONE);
			workDialog.getWindow().setGravity(Gravity.LEFT | Gravity.CENTER);
			workDialog.show();
			workDialog.initDialog(type);
		}else {
			if(!workDialog.isShowing()){
				workDialog.show();
				workDialog.initDialog(type);
			}
		}
	}
	
	public static void backHome(boolean tag){
		final String name = ((MyApplication) MyApplication.getContext()).getTopActivity();
		Log.i(TAG, name);
		if (name != null
				&& ((name.contains("com.ly.hotel.view.live.TvActivity1"))
						|| (name.contains("com.ly.hotel.view.fragments.vod.NativeVideoPlayerActivity"))
						) && tag) {

			dialog.setTitle(context.getString(R.string.exit_tips));
			dialog.setFirstButton(context.getString(R.string.yes), new OnClickListener() {
				@Override
				public void onClick(DialogInterface di, int arg1) {
					EventBus.getDefault().post(new CloseAdEvent());
					if(!name.contains("com.ly.hotel.TabHostActivity") && !name.contains("com.ly.hotel.TabHostActivity2")){
						Intent intent = new Intent();

						intent.setClass(context, TabHostActivity.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
						//必须是这个，否则SPA会奔溃
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(intent);
						if(di != null){
							di.dismiss();
						}
					}
//					TouchUtil.sendKeyCode(MyKeyEventCode.KEYCODE_MYHOME, 500, true);
				}
			});
			dialog.setSecondButton(context.getString(R.string.no), new OnClickListener() {
				@Override
				public void onClick(DialogInterface di, int arg1) {
					di.dismiss();
				}
			});
			CustomDialog d = dialog.create();
			d.getWindow().setType(LayoutParams.TYPE_SYSTEM_ALERT);
			d.show();
		}else {
				Intent intent = new Intent();
				intent.setClass(context, TabHostActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
				d.dismiss();
//			TouchUtil.sendKeyCode(MyKeyEventCode.KEYCODE_MYHOME, 500, true);
		}
		
		EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_POINT_HOME));
		
		d.dismiss();

	}
	
	public static void changeLanguage(){
		dialog.setTitle(context.getString(R.string.switch_lang_tips));
		dialog.setFirstButton(context.getString(R.string.yes), new OnClickListener() {
			@SuppressWarnings("null")
			@Override
			public void onClick(DialogInterface di, int arg1) {
				backHome(false);
				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {
			            @Override
			            public void run() {
			            	//通过产生一个空指针来重启apk，达到切换语言的功能
							//关闭自己的日志上报系统
							EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_POINT_SWITCH_LANG));
							CrashHandler.rebootNoLog = true;
							//关闭腾讯的日志上报系统
							CrashReport.closeCrashReport();
							CrashReport.closeBugly();
							
							//清理一些没用的服务
							InitActivity.stopService(context,"SPABackService",SPABackService.class);
							InitActivity.stopService(context,"MyCloudBackService",MyCloudBackService.class);
							InitActivity.stopService(context,"JxdXiaoFeiPopupWindow",JxdXiaoFeiPopupWindow.class);
							InitActivity.stopService(context,"JxdJSPopupWindow",JxdJSPopupWindow.class);
							InitActivity.stopService(context,"FxService",FxService.class);
							//自杀吧
							String fuckNanMei = null;
							fuckNanMei.equals("good");
			            }
			   	}, 800);//800毫秒后执行Runnable中的run方法
				
			}
		});
		dialog.setSecondButton(context.getString(R.string.no), new OnClickListener() {
			@Override
			public void onClick(DialogInterface di, int arg1) {
				di.dismiss();
			}
		});
		CustomDialog d = dialog.create();
		d.getWindow().setType(LayoutParams.TYPE_SYSTEM_ALERT);
		d.show();
	}

	private void testServer(){
		
		TimerTask  task= new TimerTask() {  
	         @Override  
	         public void run() {  
		    	handler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						String rv = NetworkUtil.pingHost(1, MyApplication.getHostIp());
						String lineTxt = "";
						
						BufferedReader bufferedReader = new BufferedReader(new StringReader(rv));
						String serverIp = "";
						String lost = "";
						
						try {
							while((lineTxt = bufferedReader.readLine()) != null){
								if(lineTxt.contains("packet loss")){
									String t[] = lineTxt.split(", ");
									if(t.length == 4){
										String tt[] = t[2].split(" ");
										if(tt.length == 3){
											lost = tt[0];
											lost.replace(" ", "");
										}
										
									}
								}

							    if(lineTxt.startsWith("rtt")){
//							    	Log.i("ping", lineTxt);
							    	String t[] = lineTxt.split("=");
							    	if(t.length == 2){
							    		String tt[] = t[1].split("/");
							    		if(tt.length == 4){
							    			Log.i("ping", "服务器" + serverIp + "网络延时:" + tt[1] + "ms" + ",丢包率" + lost);
							    			app.pingMs = tt[1];
							    			if(showPingMs){
							    				tips_text.setText(app.pingMs + "ms");
							    			}
							    		}
							    	}
							    }
							    
							    if(lineTxt.equals("-1")){
							    	app.pingMs = "网不通或丢包";
							    	if(showPingMs){
							    		tips_text.setText(app.pingMs);
							    	}
							    }
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
	         }
	     };  
	     
	     Timer timer = new Timer();
	     if(showPingMs){
	    	 //如果需要在小圆点上显示，就5秒一次
	    	 timer.schedule(task, 4000, 5000);    
	     } else {
	    	 timer.schedule(task, 4000, 1* 60 * 1000);  
	     }
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mFloatLayout != null) {
			mWindowManager.removeView(mFloatLayout);
		}
	}

	/* 这个就是是否显示浮动小圆点的事件接口 */
	BroadcastReceiver bottomMenuRev = new BroadcastReceiver() {
		@Override
		public void onReceive(Context cont, Intent inte) {
			int flag = inte.getIntExtra("flag", 0);
			if (flag == Constants.POINT_OPEN) {// 显示
				handler.post(new Runnable() {

					@Override
					public void run() {
						mFloatView.setVisibility(View.VISIBLE);
						tips_text.setVisibility(View.VISIBLE);
					}
				});
			} else if (flag == Constants.POINT_CLOSE) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						mFloatView.setVisibility(View.INVISIBLE);
						tips_text.setVisibility(View.INVISIBLE);
					}
				});
			} else if (flag == Constants.POINT_IDLE) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						View vv = mFloatLayout.findViewById(R.id.float_id);
						vv.setBackgroundResource(R.mipmap.point_transparent);
					}
				});
			} else if (flag == Constants.CALL_REQUEST){
				new Thread(new Runnable() {
					@Override
					public void run() {
						app.changeLight();
					}

				}).start();
			}
		}
	};
	
}
